package com.chujian.system.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chujian.framework.auth.AccessorHolder;
import com.chujian.framework.core.base.BaseServiceImpl;
import com.chujian.sys.entity.SysRole;
import com.chujian.sys.entity.SysRoleUser;
import com.chujian.system.sys.mapper.SysRoleUserMapper;
import com.chujian.system.sys.service.SysRoleService;
import com.chujian.system.sys.service.SysRoleUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户角色表 服务实现类
 *
 * @author chujian
 * @since 2021-08-26
 */
@Service
@Slf4j
public class SysRoleUserServiceImpl extends BaseServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserService {

    @Autowired
    private SysRoleService roleService;

    @Override
    public List<SysRoleUser> listRoleUser(Long roleId, boolean full) {
        return baseMapper.listRoleUser(roleId, null);
    }


    @Override
    @Transactional
    public void saveRoleUser(Long roleId, List<Long> userIds) {
        roleService.forUpdate(roleId, SysRole.class);
        for (Long userId : userIds) {
            int count = this.count(
                    new LambdaQueryWrapper<SysRoleUser>()
                            .eq(SysRoleUser::getRoleId, roleId)
                            .eq(SysRoleUser::getUserId, userId)
            );
            if (0 == count) {
                this.save(
                        new SysRoleUser().setRoleId(roleId).setUserId(userId)
                );
            }
        }
    }

    @Override
    public List<SysRoleUser> listUserRole(Long userId) {
        return baseMapper.listRoleUser(null, userId);
    }

    @Override
    public List<SysRole> getRolesByUserId() {
        Long userId = AccessorHolder.getUserId();
        QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
        wrapper.eq(null != userId, "user_id", userId);
        List<SysRoleUser> list = this.list(wrapper);

        List<Long> roleIds = list.stream().distinct().map(e -> e.getRoleId()).collect(Collectors.toList());
        List<SysRole> sysRoles = roleService.listByIds(roleIds);
        List<SysRole> roles = sysRoles.stream().filter(e -> e.getPlatId().equals(2)).collect(Collectors.toList());
        return roles;
    }
}
